<template>
    <BPTable ref='tableRef' align='center' row-key='id' name-key='name' :columns='columns' :api='pageApi' :buttons='buttons'>
        <template #status="{record}">
            <a-tag v-if="record.status == 0">待审核</a-tag>
            <a-tag color="success" v-else-if="record.status == 1">已通过</a-tag>
            <a-tag color="error" v-else-if="record.status == 2">已驳回</a-tag>
        </template>

        <template #$action="{record}">
            <template v-if="record.status == 0">
                <BTextButton type="primary" @click="passSubmit(record)">通过</BTextButton>
                <BTextButton @click="refuse(record,record.id)">驳回</BTextButton>
            </template>
        </template>
    </BPTable>


    <BDialog v-model:visible='refuseVisible' title="驳回" width='500px' :confirm='refuseSubmit'>
        <a-textarea placeholder="驳回原因" v-model:value="refuseReason" />
    </BDialog>


    <a-drawer destroyOnClose v-model:open='detailopen' title="详情" width='500px'>
        <Detail :row="currentRow" />
    </a-drawer>

    
</template>

<script lang='ts' setup>
    import { exportApi, pageApi, passApi, refuseApi } from '@/api/AlumniAuthRecord'
    import { message, Modal } from 'ant-design-vue'
    import { ref } from 'vue'
    import { useI18nStore } from '@/store/i18n'
    import { useResourceStore } from '@/store/resource'
    import { parseTime } from '@/utils'
import { schoolLevelApi } from '@/api/system/Dictionary'
import Detail from './Detail.vue'
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';



    const schoolLevelMap = ref<any>({})

    schoolLevelApi().then(r => {
        r.forEach(item => {
            schoolLevelMap.value[item.code] = item.name
        })
    })

    const detailopen = ref(false)

    const imageUrl = import.meta.env.B_NET_STATIC_URL

    const i18n = useI18nStore()
    const resourceStore = useResourceStore()

    const visible = ref(false)
    const formRef = ref()
    const dialogTitle = ref()

    const tableRef = ref()

    const currentRow = ref<any>()
    const currentCategory = ref()

    function onChangeCategory(e) {
        currentCategory.value = e
        tableRef.value.load()
    }


    const refuseVisible = ref(false)
    const refuseReason = ref<string>('')
    const currentId = ref(0)

    function refuse(row,id) {
        currentRow.value = row
        currentId.value = id
        refuseReason.value = ''
        refuseVisible.value = true
    }

    async function refuseSubmit() {
        const r = await refuseApi(currentId.value, refuseReason.value)
        if(r.success) {
            currentRow.value.status = 2
            currentRow.value.reason = refuseReason.value
            //tableRef.value.reload()
            message.success('驳回成功')
            refuseVisible.value = false
        }else {
            message.error(r.msg)
        }
    }

    async function passSubmit(record) {
        Modal.confirm({
            title : '确定通过吗',
            async onOk() {
                const r = await passApi(record.id)
                if(r.success) {
                    record.status = 1
                    //tableRef.value.reload()
                    message.success('通过成功')
                }else {
                    message.error(r.msg)
                }
            }
        })
    }


    const buttons = ref<SearchButton[]>([])

    buttons.value.push({
        button: 'export',
        async func(params) {
            const r = await exportApi(params)

            const processedData = mergeEducationData(r.data);

            // 创建 worksheet 和 workbook
            const worksheet = XLSX.utils.json_to_sheet(processedData);
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, '教育信息');

            // 生成 blob 并下载
            const wbout = XLSX.write(workbook, {
                bookType: 'xlsx',
                type: 'array',
            });

            const blob = new Blob([wbout], { type: 'application/octet-stream' });
            saveAs(blob, '申请记录.xlsx');

        }
    })

    


    const columns = ref<Column[]>([
        {
            title : '用户名',
            dataIndex : 'user',
            customRender({record}){
                return record.user.name
            }
        },

        {
            title : '学校',
            dataIndex : 'schoolName',
            customRender({record}){
                return record.schoolName
            }
        },

        {
            title : '教育层次',
            dataIndex : 'level',
            customRender({record}){
                return schoolLevelMap.value[record.level]
            }
        },

        {
            title : '毕业年份',
            dataIndex : 'graduateDate',
        },

        {
            title : '班级',
            dataIndex : 'className',
        },

        {
            title : "状态",
            dataIndex : 'status',
            // customRender({record}) {
            //     return WATER_TEST_STATUS[record.status]
            // },
            
            inSearch : true,
            type : 'select',
            options : [{label : '待审核', value: 0}, {label:'已通过', value:1}, {label:'已拒绝', value:2}],
            transform(value) {
                return Number(value)
            },
        },


        {
            title : '原因',
            dataIndex : 'reason',
        },

        {
            title : "申请时间",
            dataIndex : 'createTime',
            align : 'center',
            customRender({record}) {
                return parseTime(record.createTime)
            },
            inSearch : true,
            type : 'rangePicker',
            attrs : {
                //showTime : true,
                valueFormat : 'X'
            },
            transform(v) {
                if(v && v.length > 0) {
                    return {startTime : Number(v[0]), endTime : Number(v[1])}//[Number(v[0]), Number(v[1])]
                }
            }
        },

        {
            title : i18n.t('operation'),
            dataIndex : '$action',
            align : 'center',
            $detail(row) {
                currentRow.value = row
                detailopen.value = true
            }
        }

    
    ])


    function mergeEducationData(rawData: any[]) {
        const stageKeys = ['小学', '初中', '高中', '大学', '研究生'];
        const merged: Record<string, any> = {};

        rawData.forEach(item => {
            const phone = item['手机号码'];
            if (!merged[phone]) {
            merged[phone] = {};
            }

            // 合并基础信息
            const baseFields = Object.keys(item).filter(
            key => !['教育阶段', '毕业时间', '班级', '学校'].includes(key)
            );
            baseFields.forEach(key => {
            if (!merged[phone][key]) {
                merged[phone][key] = item[key];
            }
            });

            // 合并教育阶段信息
            const stage = item['教育阶段'];
            if (stage) {
            merged[phone][`${stage}`] = item['学校'] || '';
            merged[phone][`${stage}毕业时间`] = item['毕业时间'] || '';
            merged[phone][`${stage}班级`] = item['班级'] || '';
            }

            merged[phone]['申请日期'] = parseTime(item['申请日期'], '{y}-{m}-{d}');
            // merged[phone]['申请日期'] = new Date().toISOString().split('T')[0]; // 动态日期
        });

        return Object.values(merged);
    }


    
</script>